package br.com.sigad.persistencia.dao.representacaodigital;


import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import br.com.sigad.persistencia.dao.DAOGenerico;
import br.com.sigad.persistencia.model.RepresentacaoDigitalEntity;



public class RepresentacaoDigitalDAO extends DAOGenerico<RepresentacaoDigitalEntity> {
	
	public RepresentacaoDigitalDAO(){
		super(RepresentacaoDigitalEntity.class);
	}

	public List<RepresentacaoDigitalEntity> todasAsRepresentacoesDigitais() {
		EntityManager entityManager = getEntityManager();
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		List<RepresentacaoDigitalEntity> todas = entityManager.createQuery("from RepresentacaoDigital",RepresentacaoDigitalEntity.class).getResultList();
		transaction.commit();
		entityManager.close();
		return todas;
	}

	public boolean inserir(RepresentacaoDigitalEntity rd) {
		EntityManager entityManager = getEntityManager();
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		entityManager.persist(rd);
		transaction.commit();
		entityManager.close();
	
		return true;
	}

	public RepresentacaoDigitalEntity remover(RepresentacaoDigitalEntity rd) {
		
		Session session = getSession();
		List list = session.createCriteria(RepresentacaoDigitalEntity.class).add(Restrictions.eq("nome", rd.getNome())).list();
		
		if(!list.isEmpty()){
			session.delete(list.get(0));
		}
		session.flush();
		return (RepresentacaoDigitalEntity) list.get(0);
	}

	public boolean existe(RepresentacaoDigitalEntity rd) {
		EntityManager entityManager = getEntityManager();
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		
		Session session = (Session)entityManager.getDelegate();
		Object uniqueResult = session.createCriteria(RepresentacaoDigitalEntity.class).add(Restrictions.eq("nome", rd.getNome())).uniqueResult();
		
		transaction.commit();
		entityManager.close();
		return uniqueResult!=null;
	}


}
